package cn.jji8.mysqlUse.mySqlMap;

import cn.jji8.mysqlUse.mySqlSimpleUse.SqlConnect;
import cn.jji8.mysqlUse.mySqlSimpleUse.SqlTable;
import cn.jji8.mysqlUse.mySqlSimpleUse.column.Conlumn;
import cn.jji8.mysqlUse.mySqlSimpleUse.column.DoubleConlumn;
import cn.jji8.mysqlUse.mySqlSimpleUse.column.LongTextConlumn;
import cn.jji8.mysqlUse.mySqlSimpleUse.queryResults.QueryResults;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 基于SQl实现的StringStringMap数据结构
 * */
public class SqlStringDoubleMap {
    String name;
    LongTextConlumn keyConlumn;
    DoubleConlumn valueConlumn;
    SqlTable sqlTable;
    /**
     * 构造一个基于SQl实现的StringStringMap数据结构
     * @param sqlConnect 与数据库的连接
     * @param name 表名称
     * @param keyName 在表中key值列的名字
     * @param valueName 在表中value值列的名字
     * */
    public SqlStringDoubleMap(SqlConnect sqlConnect, String name, String keyName, String valueName) {
        this.name = name;
        Set<Conlumn> set = new HashSet<>();
        set.add(keyConlumn = new LongTextConlumn(keyName));
        set.add(valueConlumn =new DoubleConlumn(valueName));
        sqlTable = sqlConnect.getTable(name,set);
    }
    /**
     * 获取值
     * */
    public Double get(String key){
        QueryResults queryResults = sqlTable.query(valueConlumn,keyConlumn.getEqualCondition(key));
        Map<Integer,Double> map = queryResults.getResults(valueConlumn);
        for(Integer integer:map.keySet()){
            return map.get(integer);
        }
        return null;
    }
    /**
     * 添加值
     * @return 返回被修改前的value，如果之前没有value则返回null
     * */
    public Double put(String key,Double value){
        QueryResults queryResults = sqlTable.query(valueConlumn,keyConlumn.getEqualCondition(key));
        Map<Integer,Double> map = queryResults.getResults(valueConlumn);
        for(Integer integer:map.keySet()){
            Map<Conlumn,Object> objectMap = new HashMap<>();
            objectMap.put(valueConlumn,value);
            sqlTable.Update(integer,objectMap);
            return map.get(integer);
        }
        Map<Conlumn,Object> objectMap = new HashMap<>();
        objectMap.put(keyConlumn,key);
        objectMap.put(valueConlumn,value);
        sqlTable.add(objectMap);
        return null;
    }
}
